﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using System.Windows;
using Atha.Clients.Silverlight.Services;
using Atha.Clients.ViewModels;

namespace Atha.Clients.Silverlight
{
	public class ClientTestRunner : IClientTestRunner
	{
		public void ExecuteTest(string testLanguage, string testScript, ObservableCollection<TestResultViewModel> testResults)
		{
			var testClient = new AthaTestServiceClient();

			Observable.FromEventPattern<ExecuteCompletedEventArgs>(testClient, "ExecuteCompleted").Subscribe(e =>
			{
				if (e.EventArgs.Cancelled) return;

				if (e.EventArgs.Error == null)
				{
					PopulateTestResults(e.EventArgs.Result, testResults);
				}
				else
				{
					// TODO: remove mbox dependency
					MessageBox.Show("Error: " + e.EventArgs.Error.Message, "Error", MessageBoxButton.OK);
				}

				testClient.CloseAsync();
			});

			testClient.ExecuteAsync(new ExecuteTestScriptRequest { TestLanguage = testLanguage, TestScript = testScript });
		}

		private static void PopulateTestResults(IEnumerable<TestResult> testRunTestResults, ObservableCollection<TestResultViewModel> targetResults)
		{
			foreach (var testRunTestResult in testRunTestResults)
			{
				var iconPath = (string)null;

				if (!testRunTestResult.Status.HasValue)
					iconPath = @"Images/inconclusive.png";
				else if (testRunTestResult.Status.Value)
					iconPath = @"Images/success.png";
				else
					iconPath = @"Images/failure.png";

				var targetResult = new TestResultViewModel(testRunTestResult.Name, iconPath);

				targetResults.Add(targetResult);
			}
		}
	}
}
